<template>
  <div>
    <el-drawer v-model="_isOpen" size="1300" title="加入预算报价" :direction="'rtl'" modal-class="add-budget-drawer">
      <template #header>
        <h4>加入预算报价</h4>
      </template>
      <template #default>
        <el-container class="out-container">
          <!-- 左边部分 -->
          <el-aside width="500px">
            <div class="left-top">
              <p class="title">请选择关联客户</p>
              <div class="search-wrap">
                <el-input
                  v-model="customKey"
                  clearable
                  placeholder="输入业主名称/房屋地址/手机号"
                  @change="budgetCustomerListFun"
                >
                </el-input>
                <!-- <el-tooltip
                  content="跳转到CRM管理页面录入客户信息"
                  placement="bottom"
                  effect="light"
                  popper-class="following-custom-popper"
                >
                  <el-button class="add-custom" type="primary" @click="toPath('/crm/client/client-manager')">新增客户</el-button>
                </el-tooltip> -->
              </div>
            </div>

            <!-- 关联客户列表 -->
            <div class="custom-list mt4" v-loading="loading1">
              <template v-if="customList.length > 0">
                <div
                  class="custom-item"
                  :id="item.ysId"
                  :class="{ active: currObj.ysId === item.ysId }"
                  v-for="(item, index) in customList"
                  :key="index"
                  @click="clickLeftItem(item)"
                >
                  <h3 class="mb10">
                    <b>{{ item.customerName }}</b
                    ><el-divider direction="vertical" /><i>{{ "-" }}</i>
                  </h3>
                  <p class="mb10 f12">电话：{{ item.customerMobileCode }}</p>
                  <p class="f12">地址：{{ item.customerAddress }}</p>
                  <div class="active-icon" v-if="currObj.ysId === item.ysId">
                    <el-icon><CircleCheckFilled /></el-icon>
                  </div>
                </div>
              </template>
              <el-empty v-else description="暂无数据" />
            </div>
          </el-aside>

          <el-main>
            <el-container class="inner-container">
              <!-- 中间部分 -->
              <el-aside width="250px" v-loading="loading2">
                <header class="sticky-block">
                  <p class="title">预算报价模板</p>
                  <el-input
                    v-model="searchkeyTemp"
                    clearable
                    style="width: 100%"
                    placeholder="请输入预算模板名称"
                    :prefix-icon="Search"
                    @change="queryBudgetQuotationTemplateListFun"
                  />
                </header>
                <div class="temp-list">
                  <template v-if="tempList.length > 0">
                    <div
                      class="temp-item"
                      :id="item.budgetId"
                      :class="{ active: currTemp.budgetId === item.budgetId }"
                      v-for="(item, index) of tempList"
                      :key="index"
                      @click="clickCenterItem(item)"
                    >
                      <div class="temp-name text-over" :title="item.budgetName || '-'">
                        <p class="jzt-flex-center text-over">
                          <span class="text-over" style="max-width: 120px; display: inline-block" :title="item.budgetName">
                            {{ item.budgetName || "-" }}
                          </span>
                          <span>{{ `(${item.spaceCount}个空间)` }}</span>
                        </p>
                        <i class="active-icon" v-if="currTemp.budgetId === item.budgetId">
                          <el-icon><CircleCheckFilled /></el-icon>
                        </i>
                      </div>
                    </div>
                  </template>
                  <el-empty v-else :image-size="0.000001" description="暂无数据" />
                </div>
              </el-aside>

              <!-- 右边部分 -->
              <el-main v-loading="loading3">
                <header class="sticky-block">
                  <p class="title">{{ currTemp.budgetName || "-" }}</p>
                  <div style="color: #86909c; line-height: 16px">
                    <span>选择空间</span>
                    <p class="f12">当前商品规格可加入的空间与定额项</p>
                  </div>
                </header>
                <div class="space-wrap">
                  <template v-if="detail?.length > 0">
                    <div class="checkbox-wrap">
                      <el-collapse v-model="activeNames">
                        <el-collapse-item :name="index" v-for="(item, index) in detail" :key="index">
                          <template #title>
                            <div class="jzt-flex-start check-item1" @click.stop>
                              <el-checkbox
                                v-model="item.isCheckLevel1"
                                label=""
                                class="mb0"
                                style="display: flex; justify-content: flex-start; align-items: center"
                                @change="changeCheckSpace($event, item)"
                              >
                                <template #default>
                                  <div class="jzt-flex-bt" style="width: 100%">
                                    <p class="check-label">
                                      {{ item.spaceName }}
                                      <i>(包含报价项{{ item.quoteVOList?.length || 0 }}个)</i>
                                    </p>
                                  </div>
                                </template>
                              </el-checkbox>
                            </div>
                            <p class="fixed-text" style="color: #213270" v-if="item?.quoteVOList?.length > 0">
                              <!-- {{ activeNames.includes(index) ? "收起" : "展开" }} -->
                              <span class="jzt-flex-center" v-if="activeNames.includes(index)">
                                收起 <el-icon class="ml10"><ArrowDown /></el-icon>
                              </span>
                              <span class="jzt-flex-center" v-else>
                                展开 <el-icon class="ml10"><ArrowRight /></el-icon>
                              </span>
                            </p>
                          </template>
                          <div
                            class="checkList2-wrap pl34 pb25"
                            v-if="selectedCustom?.length <= 0 && item?.quoteVOList?.length > 0"
                          >
                            <p class="f12" style="color: #ea0000">如需增加个性化材料，请勿勾选以下定额！</p>
                            <el-checkbox-group v-model="item.checkList2" @change="changeCheck2(item, index, $event)">
                              <el-checkbox
                                v-for="(_item, _index) in item.quoteVOList"
                                :key="_item.contentId"
                                :label="_item.quotaName"
                                :value="_item.contentId"
                                class="mb0 mr0 check-item2"
                              >
                                <template #default>
                                  <div class="jzt-flex-bt">
                                    <p class="name f12 text-over" style="width: 80px" :title="_item.quotaName">
                                      {{ _item.quotaName || "--" }}
                                    </p>
                                    <p v-if="_item.quoteType === 1" class="info f12" style="color: #86909c">
                                      共{{ _item.totalType }}款，任选数量：{{ _item.canCheckNum }}/
                                      <span class="select-text">已选：{{ _item.checkedNum }}</span>
                                    </p>
                                    <p v-else class="info f12" style="color: #86909c">
                                      可选数量：{{ _item.canCheckNum }}/<span class="select-text"
                                        >已选：{{ _item.checkedNum }}</span
                                      >丨可选金额：¥{{ _item.canCheckMoney }}/
                                      <span class="select-text">已选：¥{{ _item.checkedMoney }}</span>
                                    </p>
                                  </div>
                                </template>
                              </el-checkbox>
                            </el-checkbox-group>
                          </div>
                        </el-collapse-item>
                      </el-collapse>
                    </div>
                  </template>

                  <el-empty v-else description="暂无数据" />
                </div>
              </el-main>
            </el-container>
          </el-main>
        </el-container>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="info" @click="cancelClick" style="width: 128px">取消</el-button>
          <el-button
            type="info"
            plain
            @click="confirmClick(false)"
            :disabled="!(currObj.ysId && currTemp.budgetId)"
            style="width: 128px"
          >
            添加
          </el-button>
          <el-button type="primary" @click="confirmClick(true)" :disabled="!(currObj.ysId && currTemp.budgetId)">
            添加并前往报价
          </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 加入当前组合条件失败 提示弹窗 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenFail"
      :type="'error-msg'"
      :title="''"
      :message="'加入当前组合条件失败！当前商品规格与当前组合条件中配置的材料无法匹配，不能添加成功，请更换其他材料或组合条件进行添加。'"
      :errorList="errorList"
      :submitBtnText="'继续撤销'"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { Search, CircleCheckFilled } from "@element-plus/icons-vue";
import useCodeArrStore from "@/store/modules/select";
import {
  getCustomList,
  chooseTemplate,
  budgetCustomerList,
  budgetCustogetCustomerListByUseSortmerList,
  queryBudgetQuotationTemplateList,
  getBudgetDetail,
  detailsAddMaterial,
  importSpaceDetails
} from "@/apis/quote-price/following";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
import ActionSubmitDialog from "@/components/ActionSubmitDialog";

const isChainTenant = JSON.parse(localStorage.getItem("userinfo"))?.isChainTenant; //判断是否是加盟商
const customKey = ref("");
const customList = ref([]); //关联客户列表
const currObj = ref({ ysId: null });
const emit = defineEmits(["update:isOpen", "submitOk"]);
const props = defineProps({
  isOpen: {
    type: Boolean,
    default: false
  },
  optionInfo: {
    type: Object,
    default: () => {
      return {
        skuObj: {},
        remark: ""
      };
    }
  },
  postData: {
    type: Object,
    default: () => {}
  },
  getSelectedCustom: {
    type: Function,
    default: null
  },
  customTotalPrice: {
    type: Number || String,
    default: "0"
  }
});
const tableRef = ref();
const treeData = ref([]); //定额工程类型tree
const currTreeNode = ref({}); //选中的工程类型树节点
const tempList = ref([]); //预算模板列表
const currTemp = ref({ budgetId: null }); //当前选中的预算模板obj
const searchkeyTemp = ref("");
const checkList = ref([]); //选中的空间list
const loading1 = ref(false);
const loading2 = ref(false);
const loading3 = ref(false);
const activeNames = ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
const _isOpenFail = ref(false); // 加入组合条件失败的提示弹窗
const errorList = ref([{}, {}]); //加入组合条件失败后的列表数据
const selectedCustom = ref([]); //获取选中的定制项

watch(
  () => props.isOpen,
  val => {
    if (val) {
      budgetCustomerListFun(); //查询left关联客户列表
      selectedCustom.value = props.getSelectedCustom() || []; //获取选中的定制项
      console.log("获取选中的定制项===", selectedCustom.value);
    }
  },
  { immediate: true }
);

const _isOpen = computed({
  get() {
    return props.isOpen;
  },
  set(value) {
    emit("update:isOpen", value);
  }
});

onMounted(() => {
  // budgetCustomerListFun(); //查询left关联客户列表
});

const clickLeftItem = item => {
  currObj.value = item;
  resetHalf(); //重置中间、右边
  queryBudgetQuotationTemplateListFun(); //查询中间的数据
};

const clickCenterItem = item => {
  currTemp.value = item;
  changeTemp(item);
  checkList.value = []; //切换预算模板时，清空已选中的空间list
};

const changeCheckSpace = (isCheck, item) => {
  if (!isCheck) {
    item.checkList2 = [];
  }
};

const changeCheck2 = (item, index, checkArr = []) => {
  if (checkArr.length > 0) {
    item.isCheckLevel1 = true;
  } else {
    // item.isCheckLevel1 = false;
  }
};

//查询left关联客户列表
const budgetCustomerListFun = () => {
  loading1.value = true;
  // budgetCustogetCustomerListByUseSortmerList({ ysState: 1, search: customKey.value })
  budgetCustomerList({ ysState: 1, search: customKey.value, sortByUse: 1 })
    .then(res => {
      if (res.code === 200) {
        customList.value = res.data || [];
        if (res.data.length > 0) {
          const obj = res.data.find(item => item.newDataCheck === 1) || res.data[0];
          obj && clickLeftItem(obj);
          nextTick(() => {
            //选中的客户滚动到可视区域
            const element = document.getElementById(obj.ysId);
            element.scrollIntoView({ behavior: "smooth", block: "center" });
          });
        }
        // manageStore.followingTotal = list.value.length;
      }
    })
    .finally(() => {
      loading1.value = false;
    });
};

/**获取已导入的模板列表 */
const queryBudgetQuotationTemplateListFun = () => {
  loading2.value = ref(true);
  queryBudgetQuotationTemplateList({ ysId: currObj.value.ysId, budgetName: searchkeyTemp.value, notShowContract: true })
    .then(res => {
      if (res.code === 200) {
        tempList.value = res.data || [];
        currTemp.value = { budgetId: null };
        detail.value = [];
        checkList.value = [];
        if (res.data.length > 0) {
          const obj = res.data.find(item => item.newDataCheck === 1) || res.data[0];
          obj && clickCenterItem(obj);
          nextTick(() => {
            const element = document.getElementById(obj.budgetId);
            element.scrollIntoView({ behavior: "smooth", block: "center" });
          });
        }
        // console.log(9999999, tempList.value);
      }
    })
    .finally(() => {
      loading2.value = false;
    });
};

/**点击某个导入的模板列表 */
const changeTemp = item => {
  currTemp.value = item;
  getBudgetDetailFun(); //查询当前模板的报价明细
};

/**查询当前模板的报价明细 */
const detail = ref([]);
const getBudgetDetailFun = () => {
  loading3.value = true;
  importSpaceDetails({ budgetId: currTemp.value.budgetId, businessSkuId: props.optionInfo.skuObj.id })
    .then(res => {
      if (res.code === 200) {
        console.log("报价明细详情===", res.data);
        detail.value = res.data;
      }
    })
    .finally(() => {
      loading3.value = false;
    });
};

const toPath = url => {
  window.open(location.protocol + "//" + window.location.hostname + url, "_blank");
};

const resetHalf = () => {
  searchkeyTemp.value = "";
  tempList.value = [];
  currTemp.value = { budgetId: null };

  searchkeyTemp.value = "";
  checkList.value = [];
  detail.value = [];
};

const reset = () => {
  currObj.value = { ysId: null };
  customKey.value = "";
  resetHalf();
};

const cancelClick = () => {
  reset();
  _isOpen.value = false;
  // emit("changeAttr");
};
const confirmClick = isPageJump => {
  let addList = [];
  detail.value?.map(item => {
    if (item?.isCheckLevel1) {
      if (item?.checkList2?.length > 0) {
        item?.checkList2?.map(_item => {
          addList.push({
            businessSkuId: props.optionInfo.skuObj.id,
            spaceId: item.spaceId,
            remark: props.optionInfo.remark === "<p><br></p>" ? "" : props.optionInfo.remark,
            contentId: _item
          });
        });
      } else {
        const obj = {
          businessSkuId: props.optionInfo.skuObj.id,
          spaceId: item.spaceId,
          remark: props.optionInfo.remark === "<p><br></p>" ? "" : props.optionInfo.remark,
          contentId: ""
        };
        /**如果选中了定制项，需要传递处理参数 */
        if (selectedCustom.value?.length > 0) {
          let customStr = "";
          selectedCustom.value?.map(obj => {
            customStr += `<p>${obj.specificationText}，增减数值：${obj.newItems}</p>`;
          });
          obj.remark = obj.remark + customStr; //定制信息拼接在备注后

          obj.customizationProduct = {
            productId: props.postData.productId,
            collectId: props.postData.collectId,
            businessSkuId: props.optionInfo.skuObj.id,
            factoryRealPrice: props.optionInfo.skuObj.factoryRealPrice,
            clinetRealPrice: props.optionInfo.skuObj.clinetRealPrice,
            coefficient: props.postData.coefficient, //定制系数
            actualAmount: props.customTotalPrice,
            productDetailList: selectedCustom.value
          };
          if (isChainTenant) {
            /**如果是加盟商，新加一个agtRate参数 */
            obj.customizationProduct.agtRate = props.postData.agtRate;
          }
        }
        addList.push(obj);
      }
    }
  });
  if (addList.length <= 0) {
    return ElMessage({
      message: "请勾选要加入的空间、定额项",
      type: "error"
    });
  }

  const params = {
    addList: addList,
    budgetId: currTemp.value.budgetId, //报价id
    templateId: currTemp.value.templateId //模板id
  };

  // console.log("加入预算报价参数===", params);
  // return;
  detailsAddMaterial(params).then(res => {
    if (res.code === 200) {
      if (res.data?.length > 0) {
        _isOpenFail.value = true; //加入失败，打开失败提示弹窗
        const errContentIds = res.data;
        const errList = [];
        detail.value.map(item => {
          item?.quoteVOList?.map(_item => {
            if (errContentIds.includes(_item.contentId)) {
              errList.push(_item);
            }
          });
        });
        errorList.value = errList;
      } else {
        ElMessage({
          message: "预算报价添加成功",
          type: "success"
        });
        if (isPageJump) {
          const routeData = router.resolve({
            path: "/quote-price/following/list",
            query: { ysId: currObj.value.ysId, budgetId: currTemp.value.budgetId, isPageJump: true }
          });
          window.open(routeData.href, "_blank");
        }
        cancelClick();
        reset();
      }
    }
  });
};

defineExpose({});
</script>

<style lang="scss">
.add-budget-drawer {
  .el-drawer {
    box-shadow: -8px 0px 16px 0px rgba(0, 38, 73, 0.1);
    border-radius: 10px 0px 0px 10px;
  }
  .el-drawer__header {
    font-size: 18px;
    color: #131414;
    padding-bottom: 20px !important;
    margin-bottom: 0 !important;
    border-bottom: 1px solid #dcdfe6;
    h4 {
      font-weight: normal;
      position: relative;
    }
  }
  .el-drawer__body {
    padding: 0 !important;

    .el-collapse-item__content {
      padding-bottom: 0;
    }
    .el-icon.el-collapse-item__arrow {
      display: none;
    }
    .search-wrap {
      display: flex;
      .el-button {
        margin-left: 4px;
      }
    }
    .add-custom.el-button:hover {
      box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.3);
    }
    .custom-list {
      padding: 0 20px 20px 20px;
      // border: 1px solid #e1e6ed;
      .custom-item {
        border: 1px solid #e1e6ed;
        padding: 16px;
        margin-bottom: 10px;
        position: relative;
        border-radius: 4px;
        cursor: pointer;
        h3 {
          color: #1d2129;
          font-weight: normal;
          b {
            font-weight: normal;
          }
          i {
            font-style: normal;
            font-size: 12px;
          }
        }
        .active-icon {
          position: absolute;
          font-size: 20px;
          right: 36px;
          top: calc(50% - 10px);
        }
        &.active {
          border-color: transparent;
          background: #eef1f4;
          box-shadow: 0px 0px 8px 0px rgba(4, 54, 114, 0.2);
        }
      }
    }
  }
  .el-drawer__footer {
    display: flex;
    justify-content: flex-end;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
    padding: 14px 20px;
    .el-button--primary {
      --el-button-bg-color: #424e66;
      border: none;
    }
    .el-button.el-button--info {
      --el-color-info: #f2f3f5;
      --el-color-white: #1d2129;
      &:hover {
        --el-button-hover-bg-color: #f2f3f5 !important;
        border-color: #f2f3f5 !important;
      }
    }
    .el-button.el-button--info.is-plain {
      --el-button-text-color: #424e66;
      --el-button-bg-color: white;
      &:hover {
        --el-button-hover-bg-color: #f2f3f5 !important;
        border-color: #c8c9cc !important;
        background-color: white !important;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  position: relative;
}
.fixed-text {
  position: absolute;
  right: 0px;
}
.select-text {
  color: #3d3d3d;
}
:deep(.check-item2) {
  display: flex !important;
  .el-checkbox__label {
    flex: 1;
  }
}
.el-button--primary.is-link.underline {
  border-radius: 0;
  border-bottom: 1px solid #213270;
}
:deep(.el-tree) {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 94px;

  .el-icon.el-tree-node__expand-icon {
    padding-left: 10px;
  }
  .el-tree-node__content {
    line-height: 32px;
    height: 32px;
    .tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      img {
        margin-right: 10px;
      }
      & > span {
        flex: 1;
        max-width: 135px;
      }
    }
  }
  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #eef1f4 !important;
    color: #1a1a1a;
    tree-node i {
      color: #1a1a1a !important;
    }
  }
}
p.title {
  line-height: 24px;
  font-size: 14px;
  padding: 8px 0;
  color: #3d3d3d;
}
:deep(.out-container) {
  height: 100%;
  .left-top {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 2;
    padding: 0 20px 10px 20px;
  }
  .el-aside {
    border-right: 1px solid #e1e6ed;
    .el-button--primary {
      --el-button-bg-color: #424e66;
      border: none;
    }
  }
  .el-main {
    padding: 0;
  }
}
:deep(.inner-container) {
  height: 100%;
  .sticky-block {
    text-align: left;
    padding: 0 20px 20px 20px;
    background-color: #edf1f4;
    .el-input__wrapper {
      background-color: white !important;
    }
  }
  .temp-list {
    .temp-item {
      line-height: 32px;
      height: 32px;
      padding: 0 20px;
      cursor: pointer;
      color: #86909c;
      .temp-name {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      &.active {
        background-color: #424e66;
        color: white;
        .active-icon {
          color: white;
          display: flex;
          align-items: center;
        }
      }
    }
  }
  .el-aside {
    background-color: #edf1f4;
  }
  .el-main {
    .el-checkbox__input.is-checked .el-checkbox__inner {
      background-color: #424e66;
    }
    .sticky-block {
      background-color: white;
    }
    .space-wrap {
      .checkbox-wrap {
        padding: 0 20px;
      }
      .el-checkbox {
        display: block;
        margin-bottom: 24px;
        .el-checkbox__label {
          padding-left: 20px;
          i {
            font-style: normal;
            color: #424e668f;
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>
